from django.conf import settings
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
import requests

from apps.address.constants import get_city_code

class Address(models.Model):
    """适配MySQL的地址模型，仅保留城市级位置信息"""
    class Meta:
        verbose_name = _("地址")
        verbose_name_plural = _("地址列表")
        indexes = [
            models.Index(fields=['user', 'is_default']),
            models.Index(fields=['province', 'city']),  # 城市查询优化
        ]

    user = models.ForeignKey(
        'accounts.User',
        on_delete=models.CASCADE,
        related_name='addresses',
        verbose_name=_("用户")
    )
    contact = models.CharField(_("联系人"), max_length=20)
    phone = models.CharField(_("手机号"), max_length=20)
    province = models.CharField(_("省份"), max_length=50, db_index=True)  # 省级索引
    city = models.CharField(_("城市"), max_length=50, db_index=True)    # 市级索引
    district = models.CharField(_("区县"), max_length=50)
    address_detail = models.TextField(_("详细地址"))
    is_default = models.BooleanField(_("默认地址"), default=False)
    
    # 移除原PostGIS字段，新增简化版坐标（可选）
    latitude = models.DecimalField(_("纬度"), max_digits=9, decimal_places=6, null=True)
    longitude = models.DecimalField(_("经度"), max_digits=9, decimal_places=6, null=True)
    is_locked = models.BooleanField(default=False, null=True, verbose_name="是否锁定")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    def __str__(self):
        return f"{self.province}{self.city}{self.district}{self.address_detail[:10]}..."

    @property
    def city_code(self):
        """生成城市标识码（如北京-110000）"""
        from .utils import get_city_code  # 需自行实现
        return get_city_code(self.province, self.city)
    
    def clean(self):
            """延迟导入校验依赖"""
            from .constants import VALID_CITIES  # 延迟导入
            if not VALID_CITIES.get((self.province, self.city)):
                raise ValidationError(f"无效的城市组合: {self.province}-{self.city}")
            
    def save(self, *args, **kwargs):
        # 自动获取大致坐标
        if not self.latitude or not self.longitude:
            self.set_approximate_coordinates()
        super().save(*args, **kwargs)
    
    def set_approximate_coordinates(self):
        """使用地理编码服务获取大致坐标"""
        from .utils import get_city_center
        
        # 1. 尝试从城市中心点获取
        city_code = get_city_code(self.province, self.city)
        if city_code:
            center = get_city_center(city_code)
            if center:
                self.latitude = center['latitude']
                self.longitude = center['longitude']
                return
        
        # 2. 使用第三方地理编码API（需要配置API_KEY）
        if hasattr(settings, 'GEOCODING_API_KEY'):
            try:
                full_address = f"{self.province}{self.city}{self.district}{self.address_detail}"
                response = requests.get(
                    f"https://restapi.amap.com/v3/geocode/geo",
                    params={
                        'key': settings.GEOCODING_API_KEY,
                        'address': full_address
                    }
                )
                result = response.json()
                if result['status'] == '1' and result['geocodes']:
                    location = result['geocodes'][0]['location'].split(',')
                    self.longitude = location[0]
                    self.latitude = location[1]
            except Exception:
                # 失败时使用默认坐标
                self.latitude = 39.9042  # 北京
                self.longitude = 116.4074